package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;

import androidx.databinding.DataBindingUtil;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityOfferOrder2Binding;
import com.sgb.kjwl.di.transport.DaggerTransportComponent;
import com.sgb.kjwl.di.transport.TransportModule;
import com.sgb.kjwl.model.entity.CarInfo;
import com.sgb.kjwl.model.entity.self.CarriageSelectEntity;
import com.swgk.core.view.entity.DriverAuthDetailEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.MapAdressDialog;
import com.sgb.kjwl.viewmodel.transport.OfferOrderModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

public class OfferOrderActivity extends AppActivity {

    ActivityOfferOrder2Binding binding;

    public static final int ORDER = 0;//接单
    public static final int OFFER = 1;//报价

    private List<CarriageSelectEntity> carModelList;
    private int carModelPosition;
    private int carPosition;
    private List<CarriageSelectEntity> carLengthList;
    private List<CarInfo> carInfo;
    private int carLengthPosition;

    // 一级联动数据
    public static List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    public static List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public static List<List<List<AddressEntity>>> opt3 = new ArrayList<>();

    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private String money = "";

    @Inject
    OfferOrderModel model;


    public static void start(Context context, int type,String goodsSourceNo,String money) {
        Intent intent = new Intent(context, OfferOrderActivity.class);
        intent.putExtra("type", type);
        intent.putExtra("goodsSourceNo", goodsSourceNo);
        intent.putExtra("money", money);
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        super.setupActivityComponent(appComponent);
        DaggerTransportComponent.builder().appComponent(appComponent)
                .transportModule(new TransportModule(this))
                .build().inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(OfferOrderActivity.this, R.layout.activity_offer_order2);
        if (getIntent().getIntExtra("type", ORDER) == ORDER) {
            binding.include.titleView.setText("接单");
            money = getIntent().getStringExtra("money");
            binding.price.setEnabled(false);

        } else if (getIntent().getIntExtra("type", ORDER) == OFFER) {
            binding.include.titleView.setText("报价");
        }
        binding.include.ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EventBus.getDefault().postSticky(MenuEvent.make().setMessageTag(EventConstant.EVENT_ORDER_FINISH));
                finish();
            }
        });
        binding.tvSureBtn.setOnClickListener(this);
        binding.hereTime.setOnClickListener(this);
        binding.endTime.setOnClickListener(this);
        binding.carLength.setOnClickListener(this);
        binding.carType.setOnClickListener(this);
        binding.carLocation.setOnClickListener(this);
        binding.carNum.setOnClickListener(this);

    }

    @Override
    protected void init() {
        model.driverAuthDetail();
        if(!TextUtils.isEmpty(money)&&money.contains("元")){
            binding.price.setText(money.substring(0,money.indexOf("元")));
            model.upData.get().setFreight(money.substring(0,money.indexOf("元")));
        }
        model.getCarInfo2();
        model.getAddressModel();

      //  model.getCarInfo();
    }

    public void setDetailData(DriverAuthDetailEntity data){

        binding.setViewModel(model);
        binding.carNum.setText(data.getCarNumber());
        binding.contect.setText(data.getName());
        binding.phone.setText(data.getTelphone());
        binding.carType.setText(data.getCarTypeName());
        binding.carLength.setText(data.getCarLenName());
       // binding.carLocation.setText(data.getProvinceName() + data.getCityName() + data.getDistrictName());
        model.upData.get().setDriverNo(data.getCarNumber());
        model.upData.get().setCarLenNo(data.getCarLenNo());
        model.upData.get().setCarTypeNo(data.getCarTypeNo());
        model.upData.get().setCityName(data.getCityName());
        model.upData.get().setCityNo(data.getCityNo());
        model.upData.get().setContrcts(data.getName());
        model.upData.get().setContrctsNumber(data.getTelphone());
        model.upData.get().setDistrictName(data.getDistrictName());
        model.upData.get().setDistrictNo(data.getDistrictNo());
        model.upData.get().setProvinceNo(data.getProvinceNo());
        model.upData.get().setProvinceName(data.getProvinceName());


    }

    @Override
    public void onMultiClick(View v) {
        super.onMultiClick(v);
        switch (v.getId()){
            case R.id.here_time:
                TimePickerView timePicker = new TimePickerBuilder(OfferOrderActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sdf.format(date);
                        binding.hereTime.setText(format);
                        model.upData.get().setInTime(DateUtils.dateTo13Timestamp(format)+"");
                      //  addChildEntity.setApproachTime(format);
                    }
                }).setRangDate(Calendar.getInstance(),null).build();
                timePicker.show();
                break;
            case R.id.end_time:
                TimePickerView timeEndPicker = new TimePickerBuilder(OfferOrderActivity.this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sdf.format(date);
                        binding.endTime.setText(format);
                        model.upData.get().setShipmentEndTime(String.valueOf(date.getTime()));
                        //  addChildEntity.setApproachTime(format);
                    }
                }).setRangDate(Calendar.getInstance(),null).build();
                timeEndPicker.show();
                break;
            case R.id.tv_sure_btn:
                pushData();
                break;
            case R.id.car_type:
                if (carModelList != null) {
                    showCarModelPop();
                } else {
                    model.carType();
                }
                break;
            case R.id.car_length:
                if (carLengthList != null) {
                    showCarLengthPop();
                } else {
                    model.carLenType();
                }
                break;
            case R.id.car_location:
          /*      if(null!=addressEntityList && addressEntityList.size()>0){
                    showCityPop("请选择地点");
                }else{
                    MToast.showToast(getActivity(),"数据未加载");
                }*/
                toMap(0,0);
                break;
            case R.id.car_num:
                if(carInfo!=null&&carInfo.size()>0) {
                    showCarInfo();
                }else{
                    model.getCarInfo();

                }
                break;
        }
    }

    private void pushData(){

        if (TextUtils.isEmpty(binding.carType.getText().toString())) {
            MToast.showToast(OfferOrderActivity.this, "请选择车型");
            return;
        } else if (TextUtils.isEmpty(binding.carLength.getText().toString())) {
            MToast.showToast(OfferOrderActivity.this, "请选择车长");
            return;
        } else if (TextUtils.isEmpty(binding.hereTime.getText().toString())) {
            MToast.showToast(OfferOrderActivity.this, "请选择时间");
            return;
        } else if (TextUtils.isEmpty(binding.price.getText().toString())) {
            MToast.showToast(OfferOrderActivity.this, "请输入价格");
            return;
        } else if(TextUtils.isEmpty(binding.carLocation.getText().toString())){
            MToast.showToast(OfferOrderActivity.this, "请选择地址");
            return;

        }else if (TextUtils.isEmpty(binding.contect.getText().toString())) {
            MToast.showToast(OfferOrderActivity.this, "请输入联系人");
            return;
        } else if (TextUtils.isEmpty(binding.phone.getText().toString())) {
            MToast.showToast(OfferOrderActivity.this, "请输入手机号");
            return;
        }else if(TextUtils.isEmpty(binding.evM.getText().toString())){
            MToast.showToast(OfferOrderActivity.this, "请输入栏高");
            return;
        }

        for(CarInfo info:carInfo){
            if(info.getCarNumber().equals(binding.carNum.getText().toString())){
                model.upData.get().setDriverNo(info.getNo());
                break;
            }
        }
        model.upData.get().setFreight(binding.price.getText().toString());
        model.upData.get().setHeightHurdle(binding.evM.getText().toString());
        model.upData.get().setContrcts(binding.contect.getText().toString());
        model.upData.get().setContrctsNumber(binding.phone.getText().toString());
        model.upData.get().setGoodsSourceNo(getIntent().getStringExtra("goodsSourceNo"));

        if (getIntent().getIntExtra("type", ORDER) == ORDER) {
            model.dirverOffer();
        } else if (getIntent().getIntExtra("type", ORDER) == OFFER) {
            model.goodsOffer();
        }

    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        addressEntityList = datas;
        initJsonData();
    }

    private void initJsonData() {

        for (int i = 0; i < addressEntityList.size(); i++) {

//            cityList = new ArrayList<>();
            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {

                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
    }

    private void showCityPop(String title) {
        CityPickView cityOption = new CityPickBuilder(OfferOrderActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName = "";
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
//                    mAreaCode = opt3.get(options1).get(options2).get(options3).getNo();
                    cityPosition3 = options3;
                }
                String content = addressEntityList.get(options1).getName() + opt2.get(options1).get(options2).getName() + areaName;
                cityPosition1 = options1;
                cityPosition2 = options2;

                if(title.equals("请选择地点")){
                    if(!TextUtils.isEmpty(areaName)){
                        model.upData.get().setDistrictName(areaName);
                        model.upData.get().setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
                    }
                    model.upData.get().setProvinceName(addressEntityList.get(options1).getName());
                    model.upData.get().setProvinceNo(addressEntityList.get(options1).getId());
                    model.upData.get().setCityName(opt2.get(options1).get(options2).getName());
                    model.upData.get().setCityNo(opt2.get(options1).get(options2).getNo());

                    binding.carLocation.setText(content);
                }
            }
        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText(title)
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    //我的车型
    public void showCarModelPop(List<CarriageSelectEntity> carModelList) {
        this.carModelList = carModelList;
        showCarModelPop();
    }
    public void showCarInfo(List<CarInfo> carInfo){
        this.carInfo=carInfo;
        if(carInfo!=null&&carInfo.size()>0) {
            showCarInfo();
        }else{
            MToast.showToast(this,"无认证车辆，请认证");
        }
    }
    public void showCarInfo2(List<CarInfo> carInfo){
        this.carInfo=carInfo;
    }
    private void showCarModelPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(OfferOrderActivity.this, (options1, options2, options3, v) -> {
            String content = carModelList.get(options1).getName();
            binding.carType.setText(content);
            carModelPosition = options1;
            model.upData.get().setCarTypeNo(carModelList.get(options1).getNo());
        }).build();
        businessOption.setPicker(carModelList);
        businessOption.setSelectOptions(carModelPosition);
        businessOption.show();
    }

    public void showCarInfo(){
        OptionsPickerView businessOption = new OptionsPickerBuilder(OfferOrderActivity.this, (options1, options2, options3, v) -> {
            String content = carInfo.get(options1).getCarNumber();
            binding.carNum.setText(content);
            carPosition = options1;
            //车型
            binding.carType.setText(carInfo.get(options1).getCarTypeName());
            model.upData.get().setCarTypeNo(carInfo.get(options1).getCarTypeNo());

            //车长
            binding.carLength.setText(carInfo.get(options1).getCarLenName());
            model.upData.get().setCarLenNo(carInfo.get(options1).getCarLenNo());

            model.upData.get().setDriverNo( carInfo.get(options1).getNo());
        }).build();
        if(carInfo!=null)
        businessOption.setPicker(carInfo);
        businessOption.setSelectOptions(carPosition);
        businessOption.show();
    }

    //我的车长
    public void showCarLengthPop(List<CarriageSelectEntity> carLengthList) {
        this.carLengthList = carLengthList;
        showCarLengthPop();
    }

    private void showCarLengthPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(OfferOrderActivity.this, (options1, options2, options3, v) -> {
            String content = carLengthList.get(options1).getName();
            binding.carLength.setText(content);
            carLengthPosition = options1;
            model.upData.get().setCarLenNo(carLengthList.get(options1).getNo());
        }).build();
        businessOption.setPicker(carLengthList);
        businessOption.setSelectOptions(carLengthPosition);
        businessOption.show();
    }

    public void toMap(double la,double lo){
        MapAdressDialog dialog= new MapAdressDialog(getActivity(),null);
        dialog.setLocation(la,lo);
        dialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialogs) {
                dialog.destoryMap();
            }
        });
        dialog.setDialogClickCallBack(new MapAdressDialog.DialogClickCallBack() {
            @Override
            public void onClickMarker(String adress, String pro, String city, String area, double latitude, double longtitude) {
                model.upData.get().setDetailAddress(adress);
                model.upData.get().setLat(latitude);
                model.upData.get().setLng(longtitude);
                model.upData.get().setProvinceName(pro);
                model.upData.get().setCityName(city);
                model.upData.get().setDistrictName(area);
                binding.carLocation.setText(adress);
                for(AddressEntity entity:addressEntityList){
                    if(entity.getName().equals(pro)){
                        MLog.d("locationOffOder","proON "+entity.getNo()+"  "+entity.getName());
                        model.upData.get().setProvinceNo(entity.getNo());
                        break;
                    }

                }
                boolean isbreak1=false;

                for (int i=0;i<opt2.size();i++){
                    for(int j=0;j<opt2.get(i).size();j++) {
                        if (opt2.get(i).get(j).getName().equals(city)) {
                            MLog.d("locationOffOder", "cityON1 " + opt2.get(i).get(j).getNo() + "  ");
                            model.upData.get().setCityNo(opt2.get(i).get(j).getNo());
                            isbreak1=true;
                            break;
                        }
                    }
                    if(isbreak1){
                        break;
                    }

                }
                boolean isbreak2=false;
                for (int i=0;i<opt3.size();i++){
                    for(int j=0;j<opt3.get(i).size();j++) {
                        for(int n=0;n<opt3.get(i).get(j).size();n++){
                            if(opt3.get(i).get(j).get(n)!=null) {
                                MLog.d("locationOffOder", "Direction " + opt3.get(i).get(j).get(n).getName() + "  ");
                                if (opt3.get(i).get(j).get(n).getName().equals(area)) {
                                    MLog.d("locationOffOder", "cityON2 " + opt3.get(i).get(j).get(n).getNo() + "  ");
                                    model.upData.get().setDistrictNo(opt3.get(i).get(j).get(n).getNo());
                                    isbreak2=true;
                                    break;
                                }
                            }
                        }
                        if(isbreak2){
                            break;
                        }
                    }
                    if(isbreak2){
                        break;
                    }
                }
            }
        });
        dialog.show();
    }
}